package com.zheng.api.server.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.zheng.api.common.constant.ApiResult;
import com.zheng.api.common.constant.ApiResultConstant;
import com.zheng.api.server.constant.WeChatConfigure;
import com.zheng.api.server.service.ApiServerUmbrellaService;
import com.zheng.api.server.service.ApiServerWechatAppService;
import com.zheng.business.dao.model.BusinessOrderUmbrellaTimecard;
import com.zheng.common.constant.Constant;
import com.zheng.common.util.*;
import com.zheng.umbrella.dao.model.UmbrellaHardwareMachine;
import com.zheng.umbrella.dao.model.UmbrellaRuleRecharge;
import com.zheng.umbrella.dao.model.UmbrellaRuleRent;
import com.zheng.upms.rpc.api.UpmsDictService;
import com.zheng.wechat.mp.dao.model.WechatMpGzuser;
import com.zheng.wechat.mp.dao.model.WechatMpNotice;
import com.zheng.wechat.mp.dao.model.WechatMpSystemAccount;
import com.zheng.wechat.mp.dao.model.WechatMpSystemAccountExample;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 微信小程序控制器
 * @author lvb
 * @date 2017-10-30
 * @version V1.0
 * @Copyright:
 */
@Controller
@Api(value = "小程序基础控制器", description = "小程序基础控制器")
@RequestMapping(value = "/v1/wechatapp")
public class ApiWechatAppController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApiWechatAppController.class);

    @Autowired
    ApiServerWechatAppService apiServerWechatAppService;
    @Autowired
    ApiServerUmbrellaService apiServerUmbrellaService;

    @Autowired
    UpmsDictService upmsDictService;

    @RequestMapping(value = "/user/login")
    @ApiOperation(value = "小程序登陆授权")
    @ResponseBody
    public String login(@RequestParam String params) {
        LOGGER.info("###### 开始接收小程序授权登录请求 ######");
        JSONObject jsonParams = JsonUtil.getJSONObjectFromJson(params);
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //临时登录凭证
        String code = jsonParams.getString("code");
        //用户非敏感信息
        String rawData = jsonParams.getString("rawData");
        //签名
        String signature = jsonParams.getString("signature");
        //用户敏感信息
        String encryptedData = jsonParams.getString("encryptedData");
        //解密算法的向量
        String iv = jsonParams.getString("iv");
        //机器码
        String machineCode = jsonParams.getString("machineCode");
        //jwid
        String jwid = jsonParams.getString("jwid");
        //取不到就从头信息取
        if(StringUtils.isEmpty(jwid)){
            jwid = request.getHeader("jwid");
        }
        if(StringUtils.isEmpty(jwid)){
            jwid = WeChatConfigure.WECHATAPP_GH;
        }
        //机器编号需要特殊处理
         machineCode = machineCode==null?"":machineCode.substring(machineCode.lastIndexOf("/")+1);if("null".equals(machineCode)){machineCode = "";}
        String ipAddress = RequestUtil.getIpAddr(request);
        return JsonUtil.object2Json(apiServerWechatAppService.login(code,rawData,signature,encryptedData,iv,ipAddress,machineCode,jwid));
    }

    @RequestMapping(value = "/user/account")
    @ApiOperation(value = "获取用户账号信息")
    @ResponseBody
    public ApiResult account() {
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            //用户id
            Integer userId = Integer.valueOf(request.getHeader("account"));
            //机器码
            String machineCode = request.getHeader("machineCode");
            //机器编号需要特殊处理
            machineCode = machineCode==null?"":machineCode.substring(machineCode.lastIndexOf("/")+1);if("null".equals(machineCode)){machineCode = "";}

            WechatMpSystemAccount account = apiServerWechatAppService.getUserAccountByUserId(userId,machineCode);

            return new ApiResult(ApiResultConstant.SUCCESS,account);
        }catch (Exception e){
            return new ApiResult(ApiResultConstant.FAILED,null);
        }
    }
    @RequestMapping(value = "/user/putFormId")
    @ApiOperation(value = "提交小程序表单id")
    @ResponseBody
    public ApiResult putFormId() {
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            try {
                //用户id
                Integer userId = Integer.valueOf(request.getHeader("account"));
                String formId = request.getParameter("formId");
                if(StringUtils.isBlank(formId) && "null".equals(formId)){
                    formId = request.getHeader("formId");
                }
                if(StringUtils.isNotBlank(formId) && !"null".equals(formId)){
                    apiServerWechatAppService.insertWechatMpWxappfromIdByUserId(userId,formId,0,1);
                }
            }catch (Exception e){
                LOGGER.error("增加用户fromid失败",e);
            }

            return new ApiResult(ApiResultConstant.SUCCESS,null);
        }catch (Exception e){
            return new ApiResult(ApiResultConstant.FAILED,null);
        }
    }

    @RequestMapping(value = "/user/getNoticetMessage")
    @ApiOperation(value = "提交小程序表单id")
    @ResponseBody
    public ApiResult getNoticetMessage() {
        try{
            List<WechatMpNotice>  notices = apiServerWechatAppService.getNoticetMessage();
            return new ApiResult(ApiResultConstant.SUCCESS,notices);
        }catch (Exception e){
            return new ApiResult(ApiResultConstant.FAILED,null);
        }
    }

    @RequestMapping(value = "/user/getMachineAndAccount")
    @ApiOperation(value = "获取设备信息及用户信息")
    @ResponseBody
    public ApiResult getMachineAndAccount(@RequestHeader String machineCode,@RequestHeader Integer account) {
        Map<String,Object> result = new HashMap<String,Object>();
        machineCode = StringUtils.isEmpty(machineCode)?"":machineCode.substring(machineCode.lastIndexOf("/")+1);
        try{
            UmbrellaHardwareMachine machine = apiServerUmbrellaService.baseSelectUmbrellaHardwareMachineByStatus(machineCode,true);
            result.put("isOnline",machine != null);
            if(machine != null ){ //设备在线
                WechatMpSystemAccount systemAccount = apiServerWechatAppService.getUserAccountByUserId(account,machineCode);
                UmbrellaRuleRent umbrellaRuleRent   = apiServerUmbrellaService.getRuleRentByMachineCode(machineCode);

                if(umbrellaRuleRent != null){
                    String dictText = upmsDictService.queryDataDictTextByValue(Constant.UM_RULE_TYPE,umbrellaRuleRent.getChargetype().toString());
                    String freeDictText = upmsDictService.queryDataDictTextByValue(Constant.UM_RULE_TYPE,umbrellaRuleRent.getFreetimetype().toString());
                    StringBuffer ruleTrans = new StringBuffer();
                    ruleTrans.append("￥").append(umbrellaRuleRent.getPrice()).append("/").append(umbrellaRuleRent.getChargelength()).append(dictText);
                    if(umbrellaRuleRent.getFreetimelength()>0) {
                        ruleTrans.append("，免费时长：").append(umbrellaRuleRent.getFreetimelength()).append(freeDictText);
                    }
                    ruleTrans.append("，不足").append(umbrellaRuleRent.getChargelength()).append(dictText).append("按").append(umbrellaRuleRent.getChargelength()).append(dictText).append("计。");
                    result.put("rent",ruleTrans.toString());
                }

                result.put("account",systemAccount);
                result.put("ruleRent",umbrellaRuleRent);
            }
            return new ApiResult(ApiResultConstant.SUCCESS,result);
        }catch (Exception e){
            result.put("isOnline",false);
            return new ApiResult(ApiResultConstant.FAILED,result);
        }
    }
}
